/*
 * @Author: Administrator
 * @Date:   2018-01-05 08:39:35
 * @Last Modified by:   Administrator
 * @Last Modified time: 2018-01-09 16:01:22
 */
import {
  observable,
  action,
  toJS,
} from 'mobx'
import getArcList from '../request/get_arc_list'
import getArcCount from '../request/get_arc_count';
import { cancelRequest } from '../request/fetch'

import { objToStrMap } from '../util/comm'
// 技术文章
class TA {
  constructor(initialState) {
    if (initialState && initialState.ta && initialState.ta.arcList) {
      this.arcList = objToStrMap(initialState.ta.arcList)
      this.total = initialState.ta.total
    } else {
      this.arcList = new Map()
      this.total = null
    }
  }
  @observable total
  @observable arcList
  @action getTa(cateId, pageSize, page = 1) {
    return new Promise((resolve, reject) => {
      const key = `list${cateId}${page}`
      if (this.arcList.get(key)) {
        resolve()
        return
      }
      const params = {
        per_page: pageSize,
        categories: cateId,
        page,
      };
      // 请求数据
      getArcList(params).then((res) => {
        if (res.status === 200) {
          const data = []
          // 只取用到的用数据
          for (const article of res.data) {
            const {
              title,
              litpic,
              excerpt,
              date,
              author,
              id,
            } = article
            const resArticle = {
              title,
              litpic,
              excerpt,
              date,
              author,
              id,
            }
            data.push(resArticle)
          }
          this.arcList.set(key, data)
          resolve()
        } else {
          reject(res.data)
        }
      }).catch(reject)
    })
  }
  @action getTotal(cateId) {
    return new Promise((resolve, reject) => {
      if (this.total) {
        resolve()
        return
      }
      const params = {
        include: cateId,
      }
      getArcCount(params).then((res) => {
        if (res.status === 200) {
          this.total = res.data[0].count
          resolve()
        } else {
          reject(res.data)
        }
      }).catch(reject);
    })
  }
  toJson() {
    return {
      arcList: toJS(this.arcList),
      total: this.total,
    }
  }
  cancel() {
    cancelRequest();
  }
}
export default TA
